<!-- 工单任务 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="任务编号" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入工单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="站点名称" prop="workstationName">
        <el-input
          v-model="queryParams.workstationName"
          placeholder="请输入站点名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="工艺流程" prop="routeCode">
        <el-input
          v-model="queryParams.routeCode"
          placeholder="请输入工艺流程"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="时间区间" prop="requestDate">
        <el-date-picker
          :clearable="false"
          v-model="valueTime"
          type="daterange"
          range-separator="至"
          start-placeholder="计划开始时间"
          end-placeholder="计划结束时间"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <vxe-table
      border
      stripe
      ref="tableRef"
      size="small"
      header-align="center"
      :row-config="rowConfig"
      :column-config="columnConfig"
      @cell-click="handleRowClick"
      :data="tableData"
    >
      <!-- <vxe-column type="checkbox" width="40" fixed="left"></vxe-column> -->
      <vxe-column type="seq" width="70" drag-sort></vxe-column>
      <vxe-column field="taskCode" show-overflow="title" align="center" title="工单编号"></vxe-column>
      <vxe-column field="taskName" show-overflow="title" align="center" title="工单名称"></vxe-column>
      <vxe-column field="colorCode" width="100" show-overflow="title" align="center" title="任务颜色" >
        <template #default="{ row }">
          <el-color-picker disabled v-model="row.colorCode"></el-color-picker>
        </template>
      </vxe-column>
      <vxe-column field="quantity" show-overflow="title" align="center" title="计划数量" ></vxe-column>
      <vxe-column field="unitOfMeasure" width="100" show-overflow="title" align="center" title="单位"></vxe-column>
      <vxe-column show-overflow="title" align="center" title="计划开始时间">
        <template #default="{ row }">
          <span>{{ parseTime(row.startTime,'{y}-{m}-{d}') }}</span>
        </template>
      </vxe-column>
      <vxe-column field="workorderCode" show-overflow="title" align="center" title="关联单据编号"></vxe-column>
      <vxe-column field="itemName" width="150" show-overflow="title" align="center" title="产品名称"></vxe-column>
      <vxe-column field="itemCode" width="150" show-overflow="title" align="center" title="产品编号"></vxe-column>
      <vxe-column field="recptDate" show-overflow="title" align="center" title="预计完成时间">
        <template #default="{ row }">
          <span>{{ parseTime(row.endTime,'{y}-{m}-{d}') }}</span>
        </template>
      </vxe-column>
      <vxe-column field="status" width="80" show-overflow="title" align="center" title="状态" >
        <template #default="{ row }">
          <dict-tag :options="dict.type.task_status" :value="row.status.toLowerCase()"/>
        </template>
      </vxe-column>
      <vxe-column field="remark"  show-overflow="title" align="center" title="操作">
        <template #default="{ row }">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            style="margin-right: 10px;"
            v-if="row.status == 'dispatched'&&row.punched !== 'true'"
            @click="handleStart(row)"
          >开工</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            v-if="row.status == 'processing'"
            @click.stop="$router.push('/mes/pro/feedback')"
          >报工</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            v-if="row.status == 'undispatch'"
            @click.stop="handleDispatch(row)"
          >派工</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            style="margin: 0 10px;"
            v-if="row.status == 'dispatch'||row.status == 'processing'"
            @click="handleFinish(row)"
          >完成</el-button>
          <el-button
            size="mini"
            type="text" 
            icon="el-icon-delete"
            v-if="row.status == 'dispatched'||row.status == 'processing'"
            @click.stop="handleClose(row)"
          >关闭</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            style="margin-left: 10px;"
            v-if="row.status == 'close'"
            @click="handleReopen(row)"
          >重启</el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <div class="app-container-footer">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick" :lazy="true">
        <el-tab-pane label="基础信息" name="1"><baseInfo :data="tableRow"/></el-tab-pane>
        <el-tab-pane label="派工信息" name="2"><dispatchInformation :data='dispatchInformationData'/></el-tab-pane>
        <el-tab-pane label="物料清单" name="3"><billOfMaterials :data="protaskTaskBomData" /></el-tab-pane>
        <el-tab-pane label="领料记录" name="4"><materialRequisitionRecord :data="protaskIssueData" /></el-tab-pane>
        <!-- <el-tab-pane label="作业指导" name="8"><homeworkGuidance :data="tableRow" /></el-tab-pane> -->
        <el-tab-pane label="报工记录" name="5"><workReportRecord :data="protaskFeedbackData" @handleClick="handleClick" /></el-tab-pane>
        <el-tab-pane label="退料记录" name="6"><returnRecord :data="protaskRtIssueData" /></el-tab-pane>
        <el-tab-pane label="执行进度" name="7"><executionRecord :data="protaskProgressData" /></el-tab-pane>
        <el-tab-pane label="质检记录" name="8"></el-tab-pane>
        <el-tab-pane label="工序流程卡" name="9"><processFlow :data="processFlowData" /></el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="title" :width="title == '关闭原因'?'400px':'800px'" append-to-body @close="handleCloseDialog">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        v-if="title == '关闭原因'"
      >
        <el-form-item label="关闭原因" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入关闭原因" />
        </el-form-item>
      </el-form>
      <el-form
        ref="form"
        :model="form1"
        :rules="rules"
        label-width="100px"
        v-else
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="班组名称" prop="groupId">
              <el-select v-model="form1.groupId" placeholder="请选择" @change="getTaskPersonList">
                <el-option
                  v-for="item in teamList"
                  :key="item.teamId"
                  :label="item.teamName"
                  :value="item.teamId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务负责人" prop="chairmanId" >
              <el-select v-model="form1.chairmanId" placeholder="请选择">
                <el-option
                  v-for="item in taskPersonList"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="其他人员" prop="others">
            <el-select v-model="form1.others" multiple placeholder="请选择">
              <el-option
                v-for="item in taskPersonList.filter(item => item.userId != form1.chairmanId)"
                :key="item.userId"
                :label="item.userName"
                :value="item.userName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remark1">
            <el-input type="textarea" v-model="form1.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="质检部门" prop="groupId1">
              <el-select v-model="form1.groupId1" placeholder="请选择" @change="getDeptList">
                <el-option
                  v-for="item in deptList"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检人员" prop="chairmanId1">
              <el-select v-model="form1.chairmanId1" placeholder="请选择">
                <el-option
                  v-for="item in deptPersonList"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remark1">
            <el-input type="textarea" v-model="form1.remark1" placeholder="请输入备注" />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProtask, getProtask, delProtask, addProtask, updateProtask } from "@/api/mes/pro/protask";
import { listTeam } from "@/api/mes/cal/team";
import { listTeammember } from "@/api/mes/cal/teammember";
import { listDept, listDeptPerson } from "@/api/system/dept";
import { 
  protaskClose,
  protaskTaskDispatch,
  protaskCheckDispatch,
  protaskFinish,
  protaskReopen,
  protaskTaskBom,
  protaskRtIssue,
  protaskProgress,
  protaskIssue,
  protaskFeedback,
  protaskGuidance,
  getDispatchInfo,
  protaskTaskStart,
  protaskInfo,
  processFlowInfo,
} from "@/api/mes/pro/workOrderTask";
import dorpTable from '@/components/dorptable/index.vue'

import baseInfo from './components/baseInfo.vue'
import billOfMaterials from './components/billOfMaterials.vue'
import materialRequisitionRecord from './components/materialRequisitionRecord.vue'
import returnRecord from './components/returnRecord.vue'
import executionRecord from './components/executionRecord.vue'
import workReportRecord from './components/workReportRecord.vue'
import homeworkGuidance from './components/homeworkGuidance.vue'
import dispatchInformation from './components/dispatchInformation.vue'
import processFlow from './components/processFlow.vue'

export default {
  name: 'WorkOrderTask',
  dicts: ['task_status'],
  components:{
    dorpTable,
    baseInfo,
    billOfMaterials,
    materialRequisitionRecord,
    returnRecord,
    executionRecord,
    workReportRecord,
    homeworkGuidance,
    dispatchInformation,
    processFlow,
  },
  data() {
    return {
      activeName: '1',
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      tableData: [],
      tableRow: [],
      valueTime: this.getDefaultDateRange(),
      dialogVisible: false,
      rules: {
        remark: [
          { required: true, message: '请输入关闭原因', trigger: 'blur' }
        ],
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        groupId: [
          {required:true, message:'请选择班组', trigger:'change'}
        ],
        chairmanId: [
          {required:true, message:'请选择任务负责人', trigger:'change'}
        ],
        groupId1: [
          {required:true, message:'请选择质检部门', trigger:'change'}
        ],
        chairmanId1: [
          {required:true, message:'请选择质检人员', trigger:'change'}
        ],
      },
      form: {},
      title: '',
      options: [{
          value: '选项1',
          label: '黄金糕'
        }, {
          value: '选项2',
          label: '双皮奶'
        }, {
          value: '选项3',
          label: '蚵仔煎'
        }, {
          value: '选项4',
          label: '龙须面'
        }, {
          value: '选项5',
          label: '北京烤鸭'
        }],
      value: '',
      value1: '',
      value2: '',
      teamList: [], //班组list
      taskPersonList: [], //任务人员list
      deptList: [], //部门list
      deptPersonList: [], //部门人员list
      form1:{
        opType: 'dispatch',
        sourceId: null,
        groupId: null,
        groupName: null,
        chairmanId: null,
        chairmanName: null,
        others: null,
        remark: '',
        opType1: 'check',
        groupId1: null,
        groupName1: null,
        chairmanId1: null,
        chairmanName1: null,
        remark1: '',
      },
      protaskIssueData: [], //领料数据
      dispatchInformationData: [], //派工数据
      protaskTaskBomData: [], //任务单BOM数据
      protaskFeedbackData: {}, //报工数据
      protaskRtIssueData: {}, //退料数据
      protaskProgressData: [], //进度数据
      processFlowData: [], //工艺工序流程数据
      columnConfig: {
        drag: true,
        resizable: true,
        storage: true,
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        align: 'center',
        headerAlign: 'center'
      },
      rowConfig: {
        drag: true,
        keyField: 'id',
        isHover: true,
        isCurrent: true,
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    cancel(){
      this.form = {}
      this.dialogVisible = false
    },
    getList(){
      this.queryParams.startTime = this.valueTime[0]
      this.queryParams.endTime = this.valueTime[1]
      listProtask(this.queryParams).then(res => {
        this.tableData = res.rows
        this.getInfoData(res.rows[0]?.taskId)
        this.$nextTick(() => {
          this.$refs.tableRef.setCurrentRow(this.tableData[0]);
        })
        // this.tableRow = res.rows[0]
        this.total = res.total
        console.log(res);
      })
      listTeam({pageNum:1,pageSize:999}).then(res => {
        this.teamList = res.rows
      })
      listDept().then(res => {
        this.deptList = res.data
      })
    },
    getTaskPersonList(val){
      listTeammember({pageNum: 1,pageSize: 10,teamId:val}).then(res => {
        this.taskPersonList = res.rows
      })
      this.teamList.forEach(item=>{
        if(item.teamId == val){
          this.form1.groupName = item.teamName
        }
      }) 
      console.log(val, this.form1);
    },
    getDeptList(val){
      listDeptPerson(val).then(res => {
        this.deptPersonList = res.data
      })
      this.deptList.forEach(item=>{
        if(item.deptId == val){
          this.form1.groupName1 = item.deptName
        }
      })
    },
    handleQuery(){
      this.getList()
      console.log(1231, this.valueTime);
    },
    resetQuery(){
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        taskCode:null,
        taskName:null,
        workstationName:null,
        routeCode:null,
      }
      this.valueTime = this.getDefaultDateRange()
      this.handleQuery()
    },
    getInfoData(taskId){
      if(!taskId) return
      protaskInfo(taskId).then(res => {
        this.tableRow = res.data
      })
    },
    // 行点击事件
    handleRowClick({row}){
      this.getInfoData(row.taskId)
      // this.tableRow = row;
      this.activeName = '1';
      console.log(row,')))))');
    },
    handleClick(tab, event){
      console.log(tab, event);
      switch (tab.name) {
        case '1':
          console.log('基础信息');
          break;
        case '2':
          getDispatchInfo(this.tableRow.taskId).then(response =>{
            this.dispatchInformationData = response.data??[];
            console.log(response)
          })
          console.log('2');
          break;
        case '3':
          protaskTaskBom(this.tableRow.taskId).then(response =>{
            this.protaskTaskBomData = response.data;
            console.log(response);
          })
          console.log('3');
          break;
        case '4':
          protaskIssue(this.tableRow.taskId).then(response =>{
            this.protaskIssueData = response.data;
            console.log(response);
          })
          console.log('4');
          break;
        case '5':
          protaskFeedback(this.tableRow.taskId).then(response =>{
            this.protaskFeedbackData = response.data;
          })
          console.log('5');
          break;
        case '6':
          protaskRtIssue(this.tableRow.taskId).then(response =>{
            this.protaskRtIssueData = response.data;
            console.log(response);
          })
          break;
        case '7':
          protaskProgress(this.tableRow.taskId).then(response =>{
            this.protaskProgressData = response.data;
            console.log(response);
          })
          break;
        case '8':
          // getRepectWorkOrder(this.tableRow.workorderId).then(response =>{
          //   this.repectWorkData = response.data;
          //   console.log(response);
          // })
          break;
        case '9':
          processFlowInfo(this.tableRow.taskId).then(response =>{
            this.processFlowData = response.data;
            console.log('processFlow', response);
          })
          break;
        default:
          break;
      }
    },
    getDefaultDateRange() {
      const today = new Date();
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(today.getDate() - 30);
      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };
      return [formatDate(thirtyDaysAgo), formatDate(today)];
    },
    // 开工
    handleStart(row){
      this.$confirm('确定要开工该任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() =>{
        protaskTaskStart(row.taskId).then(res => {
          this.$message.success('操作成功')
          this.getList()
        })
      })
      console.log(row);
    },
    handleFinish(row){
      this.$confirm('确定要完成该任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() =>{
        protaskFinish(row.taskId).then(res => {
          this.$message.success('操作成功')
          this.getList()
        })
      })
      // console.log(row);
    },
    handleDispatch(row){
      this.dialogVisible = true;
      // this.form = {...row};
      this.title = '任务派工';
      this.form1.sourceId = row.taskId;
      console.log(row);
    },
    handleClose(row){
      this.dialogVisible = true;
      this.form = {...row};
      this.title = '关闭原因';
      console.log(row);
    },
    //重启
    handleReopen(row){
      this.$confirm('确定要重启该任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() =>{
        protaskReopen({...row}).then(res => {
          this.$message.success('操作成功')
          this.getList()
        })
      })
    },
    handleCloseDialog(){
      this.dialogVisible = false;
      this.$refs.form.resetFields();
      this.form1 = {
        sourceId: null,
        opType: 'dispatch',
        groupId: null,
        groupName: null,
        chairmanId: null,
        chairmanName: null,
        others: null,
        remark: '',
        opType1: 'check',
        groupId1: null,
        groupName1: null,
        chairmanId1: null,
        chairmanName1: null,
        remark1: '',
      }
      this.form = {}
    },
    submitForm(){
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          if(this.title == '关闭原因'){
            try{
              await protaskClose({...this.form})
              this.$message.success('操作成功')
              this.getList()
              this.handleCloseDialog()
            }catch(e){
              console.log(e)
            }
          }else{
            try{
              await protaskTaskDispatch({
                opType: 'dispatch',
                sourceId: this.form1.sourceId,
                groupId: this.form1.groupId,
                groupName: this.form1.groupName,
                chairmanId: this.form1.chairmanId,
                chairmanName: this.taskPersonList.filter(item => item.userId == this.form1.chairmanId)[0].userName,
                others: this.form1.others?.join(),
                remark: this.form1.remark,
              })
              await protaskCheckDispatch({
                opType: 'check',
                sourceId: this.form1.sourceId,
                groupId: this.form1.groupId1,
                groupName: this.form1.groupName1,
                chairmanId: this.form1.chairmanId1,
                chairmanName: this.deptPersonList.filter(item => item.userId == this.form1.chairmanId1)[0].userName,
                remark: this.form1.remark1,
              })
              this.$message.success('操作成功')
              this.getList()
              this.handleCloseDialog()
            }catch(e){
              console.log(e)
            }
          }
          
          console.log(this.form);
          this.dialogVisible = false;
          this.$refs.form.resetFields();
        } 
      });
    }
  }
}
</script>

<style lang="scss" scoped>

</style>